from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session
from info.models import User, News, Category
from info.utlis.captcha.response_code import RET
from info.utlis.commond import user_login_data
from . import index_blu


@index_blu.route("/")
@user_login_data
def index():
    user = g.user
    # 2 增加右侧新闻的排行显示
    # 2.1取出右侧新闻
    news_list = list()
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)  # 查询结果对象的列表
    except Exception as error:
        current_app.logger.error(error)
    # 2.2将每一个列表对象的属性转换成可写入模板的字典格式
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 3.新闻分类传递给模板
    try:
        categorys_list = Category.query.all()
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.DBERR, errmsg="查询失败")
    categorys_dict_li = list()
    for category in categorys_list:
        categorys_dict_li.append(category.to_dict())
    # 1.3.用户登录后信息传入模板进行渲染
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "category_dict_li": categorys_dict_li
    }
    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def favicon():
    # 相当于把图标文件路径加载到静态文件夹的查找路径里面中，加载静态文件会被找到。
    return current_app.send_static_file("news/favicon.ico")


@index_blu.route("/news_list")
def news_list():
    """获取新闻首页的内容，方式为get"""
    # 1.获取参数:新闻类型,当前页码,每页显示数量
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)

    # 2.校验数据，类型校验
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.PARAMERR, errmsg="参数错误")
    # 3.查询数据
    filters = [News.status == 0]  # 存查询条件
    # cid = 1表明放置最新数据,而非分类
    # news_li = News.query.filter(News.category_id == cid).all()
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(erron=RET.DBERR, errmsg="查询数据失败")
    news_model_list = paginate.items  # 返回查询结果的模型对象列表
    total_page = paginate.pages
    current_page = paginate.page
    news_dict_li = list()
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "news_dict_li":news_dict_li,
        "total_page":total_page,
        "current_page":current_page
    }
    return jsonify(erron=RET.OK, errmsg="OK", data=data)